package com.aceitunaproject.server.counter;

import java.io.Serializable;

import com.sun.sgs.app.AppContext;
import com.sun.sgs.app.ManagedObject;
import com.sun.sgs.app.NameNotBoundException;

/**
 * A managed object counter, useful for generating IDs and such and not losing
 * the count in case the server shuts down
 * 
 * @author Federico Bergstein
 * 
 */
public class Counter implements ManagedObject, Serializable {

	private static final long serialVersionUID = 1L;

	private long count = 0;

	/**
	 * Gets the current last count
	 * 
	 * @param counterName
	 *            the counter to query
	 * @return the current last count of the specified counter
	 */
	public static long getCurrentCount(String counterName) {

		Counter counter = ((Counter) AppContext.getDataManager().getBinding(
				counterName));
		if (counter == null) {
			throw new IllegalArgumentException("Counter does not exists");
		}
		return counter.count;
	}

	/**
	 * Adds one to the counter and returns the new count
	 * 
	 * @param counterName
	 *            the counter to query and modify
	 * @return the new count
	 */
	public static long getNewCount(String counterName) {
		Counter counter = ((Counter) AppContext.getDataManager().getBinding(
				counterName));

		if (counter == null) {
			throw new IllegalArgumentException("Counter does not exists");
		}
		AppContext.getDataManager().markForUpdate(counter);
		return counter.count++;
	}

	/**
	 * Creates a new counter with the specified name
	 * 
	 * @param counterName
	 *            the name of the new counter;
	 */
	public static void createCounter(String counterName) {
		if (counterExists(counterName)) {
			throw new IllegalArgumentException("Counter already exists");
		}
		Counter counter = new Counter();
		AppContext.getDataManager().setBinding(counterName, counter);
	}

	/**
	 * Returns if a given counter exists
	 * 
	 * @param counterName
	 *            the counter to query for
	 *            @returns true if the counter exists, false if it does not
	 */
	public static boolean counterExists(String counterName)
	{ 
		try
		{
		 AppContext.getDataManager().getBinding(counterName);
		}
		catch(NameNotBoundException ex)
		{
			return false;
		}
		return true;
	}
	

}
